package com.spogher.bsc.panels;

import java.util.Iterator;
import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.spogher.bsc.data.dao.interfaces.ScoreSheetDao;
import com.spogher.bsc.data.dataobjects.Championship;
import com.spogher.bsc.data.dataobjects.ScoreSheet;
import com.spogher.bsc.data.dataobjects.Team;

public class LastResultsPanel extends Panel {

	private static final long serialVersionUID = 1L;
	private static final int MAX_RESULTS = 5;
	
	private List<ScoreSheet> lastScoreSheets;
	@SpringBean
	private ScoreSheetDao scoreSheetDao;

	public LastResultsPanel(String id) {
		super(id);
		lastScoreSheets = scoreSheetDao.findLasts(MAX_RESULTS);
		createBodyComponents();
	}
	
	public LastResultsPanel(String id, Championship championship) {
		super(id);
		lastScoreSheets = scoreSheetDao.findByChampionship(championship, MAX_RESULTS);
		createBodyComponents();
	}
	
	public LastResultsPanel(String id, Team team) {
		super(id);
		lastScoreSheets = scoreSheetDao.findByTeam(team, MAX_RESULTS);
		createBodyComponents();
	}

	private void createBodyComponents() {		
		addOrReplaceDataView();		
		
	}

	private void addOrReplaceDataView() {
		IDataProvider<ScoreSheet> lastResultsDataProvider = new IDataProvider<ScoreSheet>() {
			
			private static final long serialVersionUID = 1L;

			public void detach() {
				
			}
			
			public int size() {
				return lastScoreSheets.size();
			}
			
			public IModel<ScoreSheet> model(ScoreSheet object) {
				return new CompoundPropertyModel<ScoreSheet>(object);
			}
			
			public Iterator<? extends ScoreSheet> iterator(int first, int count) {
				return lastScoreSheets.iterator();
			}
		};
		
		DataView<ScoreSheet> lastResultsDataView = new DataView<ScoreSheet>("lastResultsDataView", lastResultsDataProvider) {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(Item<ScoreSheet> item) {
				item.add(new Label("date"));
				item.add(new Label("homeTeam.championship.name"));
				item.add(new Label("homeTeam.name"));
				item.add(new Label("homeTeamScore"));
				item.add(new Label("awayTeamScore"));
				item.add(new Label("awayTeam.name"));
			}
		};
		
		addOrReplace(lastResultsDataView);
	}

}
